package com.flyduck.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flyduck.domain.SysLog;
import com.flyduck.mapper.SysLogMapper;
import com.flyduck.util.RequestUtil;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: flyduck-admin
 * @description: 日志切面
 * @author: flyduck
 * @create: 2020-05-10 19:12
 **/
public class SystemAspect {

    @Autowired
    private SysLogMapper sysLogMapper;

    public void writeLog(JoinPoint joinPoint) throws JsonProcessingException {
        System.out.println("记录日志");
        SysLog sysLog = new SysLog();
        //设置操作时间
        sysLog.setTime(new Date());
        //设置IP地址 request 添加拦截器 获取请求对象
        HttpServletRequest request = RequestUtil.getRequest();
        if(request != null){
            String ip = request.getRemoteAddr();
            sysLog.setIp(ip);
        }
        //设置方法和参数
        //=====方法
        //==========获取目标方法的全路径
        String methodPath = joinPoint.getTarget().getClass().getName();
        //==========获取方法的名称
        String methodName = joinPoint.getSignature().getName();
        String method = methodPath+":"+methodName;
        sysLog.setMethod(method);
        //=====参数
        String params = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
        sysLog.setParams(params);
        sysLogMapper.insert(sysLog);


    }
}
